// https://www.luogu.com.cn/problem/P1379
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
using namespace std;
using ll = long long;
const int inf = 0x3f3f3f3f;
#define rf(i, n) for (int i = 1; i <= (n); ++i)
int rad(); // read int
const int max_size = 5 + 10;
const int maxn = 5 + 1e6;

struct Node {
    int id, dis, remain; // from dis, to dis
    bool operator<(const Node &r) const { return dis + remain > r.dis + r.remain; }
};
int tot, ans;
char state[maxn][max_size];
char tar[max_size] = "123804765";

ll Hash(char *a) {
    ll back = 0;
    for (int i = 0; i < 9; ++i)
        back = back * 10 + a[i] - '0';
    return back;    
}

map<ll, bool> visit;

int dx[] = {0, -1, 0, 1, 0};
int dy[] = {0, 0, 1, 0, -1};
inline bool inside(int x, int y) { return 0 <= x && x <= 2 && 0 <= y && y <= 2; };
/*
012
345
678
*/
priority_queue<Node> qe;

int cnt_dis(int id) {
    int back = 0;
    for (int i = 0; i < 9; ++i)
        if (state[id][i] != tar[i]) back++;
    return back;
}

int main() {
    scanf("%s", state[++tot]);
    if (strncmp(state[tot], tar, 9) == 0) {
        puts("0");
        return 0;
    }
    qe.push({1, 0, cnt_dis(1)});
    while (!qe.empty()) {
        auto tmp = qe.top();
        qe.pop();
        char *now = state[tmp.id];

        int p = 0;
        while (now[p] != '0')
            ++p;
        int x = p / 3, y = p % 3;
        rf(i, 4) {
            int nx = x + dx[i], ny = y + dy[i];
            if (!inside(nx, ny)) continue;
            strncpy(state[++tot], now, 9);
            swap(state[tot][p], state[tot][nx * 3 + ny]);
            if (visit[Hash(state[tot])] == 1) {
                --tot;
                continue;
            }
            if (strncmp(state[tot], tar, 9) != 0) {
                qe.push({tot, tmp.dis + 1, cnt_dis(tot)});
                visit[Hash(state[tot])] = 1;
            } else {
                printf("%d", tmp.dis + 1);
                return 0;
            }
        }
    }
}

int rad() {
    int back = 0, ch = 0, neg = 0;
    for (; ch < '0' || ch > '9'; ch = getchar())
        neg = ch == '-';
    for (; ch >= '0' && ch <= '9'; ch = getchar())
        back = (back << 1) + (back << 3) + (ch & 0xf);
    return (back ^ -neg) + neg;
}